package com.ejuornal.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.velocity.VelocityContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ejuornal.bean.Role;
import com.ejuornal.bean.User;
import com.ejuornal.bean.UserExt;
import com.ejuornal.bean.vo.PermissionVO;
import com.ejuornal.service.PermissionService;
import com.ejuornal.service.UserExtService;
import com.ejuornal.service.UserService;
import com.ejuornal.springutil.SpringUtil;
import com.ejuornal.util.Constants;
import com.ejuornal.util.EmailSender;
import com.ejuornal.util.MD5;
import com.ejuornal.util.StrToIntArray;
import com.ejuornal.util.VelocityUtil;

@Component("userAction")
@Scope("prototype")
public class UserAction extends BaseAction<User> {
	private static final long serialVersionUID = 1L;
	private UserService userService;
	private User user;
	private String userIdStr = null;// 详情id
	private int roleId;
	private int userId;
	private String userNameStr;
	private String userName;// 注册用户名-验证是否存在
	private String emailStr;// 注册邮箱-验证是否存在
	private UserExtService userExtService = null;
	private UserExt userExt;
	private String emailTest;
	private UserExtService useExtService;
	private PermissionService permissionService;
	private List<PermissionVO> pv;

    public String login() {
    	System.out.println("登陆操作。。。。。。。。 ");
		HttpSession session = getSession2();
		if (session.getAttribute(Constants.USERSESSION) != null) {
		    preAction = (String) session.getAttribute("preAction");
		    prePage = (String) session.getAttribute("prePage");
		    System.out.println("preAction---->>>>>"+preAction);
		    System.out.println("prePage------->>>>>"+prePage);
		    if(preAction == null || "".equals(preAction)){
		        return "index_1";
		    } else {
		        return SUCCESS;
		    }
		} else {
			String randomFront = super.getRequest().getParameter("random");
			String randomBack = (String) super.getSession().get("random");
			System.out.println("randomFront------>>>>>"+randomFront);
			System.out.println("randomBack----->>>>"+randomBack);
			if (randomBack != null && randomFront.toLowerCase().equals(randomBack.toLowerCase())) {
				String password = MD5.MD5Encode(user.getPassword());
				System.out.println("密码:"+password);
				user.setPassword(password);
				User user1 = null;
				if(user.getEmail().indexOf("@") == -1) {	//判断用户是否用用户名登录
				   user1 = userService.findByUserName(user.getEmail());
				} else {	//用邮箱登录的验证
				   user1 = userService.validate(user.getEmail());
				}
				if(user1 == null) {
				    super.getRequest().setAttribute("alert", "用户名或邮箱不存在");
                    return INPUT;
				}
				// 默认黑名单或者未验证的用户角色信息为1
				if (user1.getPassword() != null
						&& password.equals(user1.getPassword())
						&& user1.getRoleId() != 1) {
					session.setAttribute(Constants.USERSSSIONID,
							user1.getUserId());
					session.setAttribute(Constants.USERSESSION,
							user1.getUserName());
					session.setAttribute(Constants.USERSESSIONROLEID, user1.getRoleId());
					session.setAttribute(Constants.USERSESSIONEMAIL, user1.getEmail());
					
					preAction = (String) session.getAttribute("preAction");
		            prePage = (String) session.getAttribute("prePage");
		            if(prePage == null || "".equals(prePage)){
		                return "index_1";
		            } else {
		                return SUCCESS;
		            }
				} else {
					// 有错误时候前台弹出对话框，提示用户密码错误
					super.getRequest().setAttribute("alert", "*密码错误");
					return INPUT;
				}
			} else {
				super.getRequest().setAttribute("alert", "*验证码错误");
				return INPUT;
			}
		}}

    public String deleteUser(){
   	 	userService.delete(StrToIntArray.ChangeStrToIntArray(userIdStr));
   	 	return "success";
    }
    public String register_1() {
        String savePath = super.getURl();
        HttpSession session = super.getSession2();
        
        boolean result = userService.isExists(user.getUserName());
        if(result) {
        	return "error_fresh";
        }
        
        userService.add(user);
        
        String vm = "vm/register_email.vm";
        VelocityContext context = new VelocityContext();
        
        session.setAttribute(Constants.FINDPWDSESSION, session.getId());
        session.setMaxInactiveInterval(60 * 60 * 24);
       
        String url = savePath + "user/user_register_2?session=" + session.getId() + "&user_name=" + user.getUserName();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = sdf.format(date);
        
        context.put("userName", user.getUserName());
        context.put("currentDate", date1);
        context.put("url", url);

        
        
        String mailContent = "";
        try {
            mailContent = VelocityUtil.init_2(context, vm);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        EmailSender.send(user.getEmail(), "中国刊网--激活账户", mailContent, "text/html");
        return SUCCESS;
    }
    
    public String register_2() {
//    	String session = (String)super.getSession2().getAttribute(Constants.FINDPWDSESSION);
//    	String session_2 = super.getRequest().getParameter("session");
    	/*if(session == null || session_2 == null || !session.equals(session_2)) {
    	    return ERROR;
    	}*/
        String userName = super.getRequest().getParameter("user_name");
        user = new User();
        user.setUserName(userName);
        user.setRegisteDate(new Date());
        user.setRoleId(2);
        
        if(userService.update(user) == true) {
        	User user = userService.findByUserName(userName);
        	if(!userExtService.isUserExtExist(user.getUserId())) {
        		userExt = new UserExt();
            	userExt.setUserId(user.getUserId());
            	userExtService.add(userExt);
            	
            	return SUCCESS;
        	} else {
        		return "error_404";	//控制激活链接，一次失效
        	}
            
        } else {
            return ERROR;
        }
    }
    
    public String find_pwd_1() {
        String email = super.getRequest().getParameter("email");
        User u = userService.validate(email);
        if(u != null) {
            String savePath = super.getURl();
            String vm = "vm/find_pwd_email.vm";
            VelocityContext context = new VelocityContext();
            HttpSession session = super.getSession2();
            session.setAttribute(Constants.FINDPWDSESSION, session.getId());
            session.setMaxInactiveInterval(60 * 60 * 24);
            String url = savePath + "html/userFindPwd3.jsp?session=" + session.getId() + "&id=" + u.getUserId() + "&userName=" + u.getUserName();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date1 = sdf.format(date);
            
            context.put("userName", u.getUserName());
            context.put("currentDate", date1);
            context.put("url", url);
            
            String mailContent = "";
            try {
                mailContent = VelocityUtil.init_2(context, vm);
            } catch (IOException e) {
                e.printStackTrace();
            }
            EmailSender.send(u.getEmail(), "中国刊网--找回密码", mailContent, "text/html");
        }
        return SUCCESS;
    }
    
    
    public String find_pwd_2() {
        userService.resetPwd(user, user.getPassword());
        return SUCCESS;
    }
    
    public String exit() {
    	super.getSession().remove(Constants.USERSESSION);
    	super.getSession().remove(Constants.USERSSSIONID);
    	super.getSession().remove(Constants.USERSESSIONROLEID);
    	super.getSession().remove(Constants.USERSESSIONEMAIL);
    	super.getSession().remove("preAction");
    	super.getSession().remove("prePage");
    	return SUCCESS;
    }
   
    public String menuList() {
//        roleId = (Integer) super.getRequest().getSession().getAttribute(Constants.USERSESSIONROLEID);
        roleId = userService.findById(super.getUserIdBySession()).getRoleId();
        HttpSession session = super.getSession2();
        session.setAttribute(Constants.USERSESSIONROLEID, roleId);
        pv = permissionService.findPermissionVO(roleId);
        return SUCCESS;
    }
    
    
// 会员列表显示   
    public String listUser() {
   	 String  email = emailTest.trim();
   	 String url ="user/listUser?emailTest=test&";
        if(!email.equals("test")){
       	 pages=userService.findByEmail((page - 1) * 10, url, user.getEmail());
       	 return SUCCESS;
        }else {
       	 pages=userService.findAll((page - 1) * 10, url);
       	 return  SUCCESS;
		}
	}

	// 查看会员所有信息
	public String detailUser() {
		userService = (UserService) SpringUtil.getBean("userService");
		userExtService = (UserExtService) SpringUtil.getBean("userExtService");
		user=userService.findById(userId);
		userExt = userExtService.findByUserId(userId);
		return SUCCESS;
	}

	/**
	 * 查找一个用户的主表
	 * 
	 * @return
	 */
	public String  findById(){
		userService=(UserService) SpringUtil.getBean("userService");
		user=userService.findById(userId);
		return SUCCESS;
	}

	/**
	 * 更新一个用户的角色状态
	 * 
	 * @return
	 */
	public String updateRole() {
		
		boolean flag = userService.update(user);
		return SUCCESS;
	}
	/**
	 * 判断用户名是否存在
	 * @return
	 */
	public String userNameIsExists(){
		if(userNameStr != null && !("".equals(userNameStr))){
			user = userService.findByUserName(userNameStr);
			if(user != null) {
	            dataMap.put("success", "1");
	        } else {
	            dataMap.put("success", "0");
	        }
		}else {
	        dataMap.put("success", "0");
	    }
	    return SUCCESS;
	}

	public String emailIsExists() {
	    dataMap.clear();
	    if(emailStr != null && !"".equals(emailStr)) {
	        user = userService.findByEmail(emailStr);
	        if(user != null) {
	            dataMap.put("success", "1");
	        } else {
	            dataMap.put("success", "0");
	        }
	    } else {
	        dataMap.put("success", "0");
	    }
	    return SUCCESS;
	}

//	查看会员密码
	public String detailPassword()
	{
		userService=(UserService) SpringUtil.getBean("userService");
//		user=userService.findById(Integer.parseInt(userIdStr));
		user=userService.findById(super.getUserIdBySession());
	    return "success";
	}

	/*
	 * 修改密码
	 */
	public String modPwd() {
		userService = (UserService) SpringUtil.getBean("userService");
		String password = MD5.MD5Encode(user.getPassword());
		user.setPassword(password);
		user.setUserId(super.getUserIdBySession());
		userService.updatePwd(user);
		
		return SUCCESS;
	}


	// 查看会员便于修改角色
	/*
	 * public String findById()
	 * 
	 * { userService=(UserService) SpringUtil.getBean("userService"); //
	 * user=userService.findById(Integer.parseInt(userIdStr));
	 * user=userService.findById(Integer.parseInt(userIdStr)); //
	 * System.out.println("ff   password"+user.getPassword()); return "success";
	 * }
	 */
	// 查看会员所有信息
	/*
	 * public String detailUser()
	 * 
	 * { userService=(UserService) SpringUtil.getBean("userService");
	 * user=userService.findById(Integer.parseInt(userIdStr));
	 * userExtService=(UserExtService) SpringUtil.getBean("userExtService");
	 * userExt=userExtService.findByUserId(Integer.parseInt(userIdStr)); return
	 * "success"; }
	 */
	/*
	 * 更改会员角色
	 */
	/*
	 * public String updateRole()
	 * 
	 * { userService = (UserService) SpringUtil.getBean("userService"); //
	 * user=userService.findById(Integer.parseInt(userIdStr));
	 * System.out.println("action  roleId"+user.getRoleId());
	 * userService.updateRole(user); return SUCCESS; }
	 */
	public UserService getUserService() {
		return userService;
	}

	@Resource(name = "userService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public int getRoleId() {
		return roleId;
	}

	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}

	public String getUserIdStr() {
		return userIdStr;
	}

	public void setUserIdStr(String userIdStr) {
		this.userIdStr = userIdStr;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getEmailStr() {
		return emailStr;
	}

	public void setEmailStr(String emailStr) {
		this.emailStr = emailStr;
	}

	public UserExt getUserExt() {
		return userExt;
	}

	public void setUserExt(UserExt userExt) {
		this.userExt = userExt;
	}

	public UserExtService getUserExtService() {
		return userExtService;
	}

	@Resource(name = "userExtService")
	public void setUserExtService(UserExtService userExtService) {
		this.userExtService = userExtService;
	}

	public String getEmailTest() {
		return emailTest;
	}

	public void setEmailTest(String emailTest) {
		this.emailTest = emailTest;
	}

	public UserExtService getUseExtService() {
		return useExtService;
	}
	@Resource(name="userExtService")
	public void setUseExtService(UserExtService useExtService) {
		this.useExtService = useExtService;
	}
	
	public PermissionService getPermissionService() {
        return permissionService;
    }

	@Resource(name="permissionService")
    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }
	
	public List<PermissionVO> getPv() {
        return pv;
    }

    public void setPv(List<PermissionVO> pv) {
        this.pv = pv;
    }

	public String getUserNameStr() {
		return userNameStr;
	}

	public void setUserNameStr(String userNameStr) {
		this.userNameStr = userNameStr;
	}
    
}
